package com.ifras.project;

import java.math.BigDecimal;

import android.app.Activity;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity implements GPSCallback {
	private GPSManager gpsManager = null;
	private double speed = 0.0;
	Boolean isGPSEnabled = false;
	LocationManager locationManager;
	double currentSpeed, kmphSpeed;
	TextView txtview, GPS;
	GPSTracker gpsTracker;
	PolygonLogic logic;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		txtview = (TextView) findViewById(R.id.info_message);
		GPS = (TextView) findViewById(R.id.textView1);
		txtview.setText(getString(R.string.info));
		GPS.setText(getString(R.string.info));

		locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
		gpsManager = new GPSManager(MainActivity.this);
		isGPSEnabled = locationManager
				.isProviderEnabled(LocationManager.GPS_PROVIDER);
		
		logic=new PolygonLogic(MainActivity.this);
		
		if (isGPSEnabled) {
			gpsManager.startListening(getApplicationContext());
			gpsManager.setGPSCallback(this);
		} else {
			gpsManager.showSettingsAlert();
		}

	}

	@Override
	public void onGPSUpdate(Location location) {
		gpsTracker = new GPSTracker(this);
		speed = location.getSpeed();
		currentSpeed = round(speed, 3, BigDecimal.ROUND_HALF_UP);
		kmphSpeed = round((currentSpeed * 3.6), 3, BigDecimal.ROUND_HALF_UP);
		txtview.setText(kmphSpeed + " km/h");

		GPS.setText("Latitude: " + gpsTracker.getLatitude() + "\nLongitude: "
				+ gpsTracker.getLongitude());

		logic.givenCoordinateIsInside(gpsTracker.getLatitude(), gpsTracker.getLongitude());
	}

	@Override
	protected void onDestroy() {
		gpsManager.stopListening();
		gpsManager.setGPSCallback(null);
		gpsManager = null;
		super.onDestroy();
	}

	public static double round(double unrounded, int precision, int roundingMode) {
		BigDecimal bd = new BigDecimal(unrounded);
		BigDecimal rounded = bd.setScale(precision, roundingMode);
		return rounded.doubleValue();
	}
}